/* eslint-disable prefer-destructuring */
import { computed, defineComponent, PropType } from 'vue';
import { useNamespace } from '@ibiz-template/vue3-util';
import { ISearchBarFilter, ISearchBarGroup } from '@ibiz/model-core';
import {
  ISearchCondEx,
  isSimpleItems,
  SearchCondEx2filterNode,
} from '@ibiz-template/runtime';
import { FilterSearchBarController } from '../../filter-search-bar.controller';
import FilterGroup from '../filter-group/filter-group';
import FilterItem from '../filter-item/filter-item';

/**
 * 过滤条件组件
 * - 过滤条件的入口组件
 */
export const FilterCond = defineComponent({
  name: 'FilterCond',
  props: {
    id: {
      type: String,
      required: true,
    },
    controller: {
      type: Object as PropType<FilterSearchBarController>,
      required: true,
    },
  },
  emits: ['change'],
  setup(props, { emit }) {
    const ns = useNamespace('filter-cond');
    const c = props.controller;

    /**
     * 模型
     */
    const model = computed(() => {
      return (
        c.state.sysFilter.find(s => s.id === props.id) ||
        c.state.fieldFilter.find(f => f.id === props.id)
      );
    });

    /**
     * 条件数据
     */
    const data = computed(() => {
      return c.state.conds[props.id];
    });

    /**
     * 过滤值改变
     * @param item
     */
    const onChange = (item: IData): void => {
      if (c.state.conds[props.id].valueOP === 'EXISTS') {
        c.state.conds[props.id].children[0].value = item.val;
      }
      emit('change', item);
    };

    /**
     * 初始化过滤条件项
     * - 根据过滤条件类型初始化过滤值
     */
    const initCond = (): void => {
      if (!Object.prototype.hasOwnProperty.call(c.state.conds, props.id)) {
        let newVal: IData = {};
        if (model.value?.itemType === 'GROUP') {
          const group = model.value as ISearchBarGroup;
          newVal = {
            leaf: false,
            nodeType: 'GROUP',
            logicType: 'AND',
            children: [],
          };
          if (group.data) {
            const item = JSON.parse(group.data);
            if (item.theme_model?.searchconds) {
              newVal = item.theme_model.searchconds.map((cond: ISearchCondEx) =>
                SearchCondEx2filterNode(cond),
              )[0];
            }
          }
        }
        if (model.value?.itemType === 'FILTER') {
          if (isSimpleItems(model.value as ISearchBarFilter)) {
            const xx = c.filterControllers?.find(
              item => item.key === model.value?.id,
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
            ) as any;
            const filter = model.value as ISearchBarFilter;
            newVal = {
              nodeType: 'ITEMS',
              children: [
                {
                  nodeType: 'FIELD',
                  field: xx?.subFieldName.toLowerCase(),
                  valueOP: xx?.subValueOP,
                  value: null,
                },
              ],
              leaf: true,
              field: filter.appDEFieldId
                ? filter.appDEFieldId.toLowerCase()
                : filter.id!,
              valueOP: null,
              value: null,
            };
          } else {
            const filter = model.value as ISearchBarFilter;
            newVal = {
              leaf: true,
              nodeType: 'FIELD',
              field: filter.appDEFieldId
                ? filter.appDEFieldId.toLowerCase()
                : filter.id!,
              valueOP: null,
              value: null,
            };
          }
        }
        Object.assign(c.state.conds, { [props.id]: newVal });
      }
    };

    initCond();

    /**
     * 根据条件类型绘制子组件
     *
     * @return {*}  {(JSX.Element | undefined)}
     */
    const renderContent = (): JSX.Element | undefined => {
      if (model.value?.itemType === 'GROUP') {
        return (
          <FilterGroup
            data={data.value}
            model={model.value as ISearchBarGroup}
            controller={props.controller}
            onChange={onChange}
          ></FilterGroup>
        );
      }
      if (
        model.value?.itemType === 'FILTER' ||
        model.value?.itemType === 'ITEMS'
      ) {
        return (
          <FilterItem
            showLabel={false}
            data={data.value}
            model={model.value as ISearchBarFilter}
            controller={props.controller}
            onChange={onChange}
          ></FilterItem>
        );
      }
    };

    return {
      ns,
      renderContent,
    };
  },
  render() {
    return <div class={this.ns.b()}>{this.renderContent()}</div>;
  },
});
export default FilterCond;
